package com.sluggard.security.core.manage;

import com.sluggard.common.utils.GsonUtil;
import com.sluggard.security.core.utils.RedisUtil;
import com.sluggard.security.manage.model.vo.SecurityUser;
import com.sluggard.security.properties.SecurityConfigProperties;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SessionManage implements ApplicationContextAware {

    private static final String USER_SESSION = "USER_CONTEXT:";

    private static SecurityConfigProperties securityConfigProperties;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SessionManage.securityConfigProperties = applicationContext.getBean(SecurityConfigProperties.class);
    }

    /**
     * 设置session信息
     *
     * @param token
     * @param userInfo
     */
    public static void setSession(String token, SecurityUser userInfo) {
        RedisUtil.set(USER_SESSION + token, GsonUtil.toJsonFilterNullField(userInfo), securityConfigProperties.getSessionTimeOut());
    }

    /**
     * 获取session信息
     *
     * @param token
     * @return
     */
    public static SecurityUser getSession(String token) {
        Object obj = RedisUtil.get(USER_SESSION + token);
        if(Objects.isNull(obj)){
            return null;
        }
        SecurityUser userInfo = GsonUtil.fromJson(obj.toString(), SecurityUser.class);
        // 使用后进行续费
        setSession(token, userInfo);
        return userInfo;
    }

    /**
     * 移除session信息
     *
     * @param token
     */
    public static void removeSession(String token) {
        RedisUtil.del(USER_SESSION + token);
    }

    /**
     * 在线总人数
     *
     * @return
     */
    public static Integer live() {
        AtomicInteger liveNum = new AtomicInteger(0);
        RedisUtil.scanKeys(USER_SESSION + "*", item -> {
            liveNum.incrementAndGet();
        });
        return liveNum.get();
    }


}
